package com.demo.mutilThread;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "test.threadPool")
class ThreadPool {
    //任务队列
    private BlockingQqeuePollImplement<Runnable> taskQueue;
    //线程集合
    private HashSet<Worker> workers = new HashSet<>();
    //核心线程数
    private int coreSize;
    //获取任务的超时时间
    private long timeout;
    private TimeUnit timeUnit;
    //添加属性
    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeUnit = timeUnit;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQqeuePollImplement(queueCapcity);
        this.rejectPolicy = rejectPolicy;
    }

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity) {
        this.coreSize = coreSize;
        this.timeUnit = timeUnit;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQqeuePollImplement(queueCapcity);
    }


    //执行任务
    public void execute(Runnable task) {
        //当线程数没有超过coresize时，直接交给worker对象执行
        //如果任务数超过coresize时 加入任务队列暂存

        //workers是非线程安全的
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                log.debug("新增worker{},{}", worker, task);
                workers.add(worker);
                worker.start();
            } else {
                taskQueue.put(task);
                taskQueue.tryPut(rejectPolicy, task);
                // 1死等
                //2 超时等待
                //3 让调用者放弃任务执行
                // 4 让调用者抛出异常
                //5 让调用者自己执行任务
                //加入写死在该类中那么则不方便拓展，我们可以让调用者来选择（当队列满了，调用者采用什么模式），这就使用了设计模式中的策略模式
                //就是将操作抽象成一个接口，具体的实现由调用者来实现
            }
        }

    }

    class Worker extends Thread {
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
//             super.run();
            //执行任务
//             1.当task不为空执行任务
//             2.当task执行完毕，接着从任务队列中获取任务并执行
//             while (task != null || (task = taskQueue.take()) != null) {
            while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
                //替换为有超时时间的方法，如果超时就会走下面的程序移除worker
                try {
                    log.debug("正在运营。。。{}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }

            synchronized (workers) {
                log.debug("worker被移除{}", this);
                workers.remove(this);
            }
        }
    }

}

/**
 * 添加poll
 */
@Slf4j
public class BlockingQqeuePollImplement<T> {
    //1 任务队列
//    private Deque<T> queue = (Deque<T>) new ArrayQueue<T>(5);
    private Deque<T> queue = new ArrayDeque(5);

    //2 锁
    private ReentrantLock lock = new ReentrantLock();
    //3 生产者条件变量
    private Condition fullWaitSet = lock.newCondition();
    //4 消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();
    //5 容量
    private int capcity;

    public BlockingQqeuePollImplement(int queueCapcity) {
        this.capcity = queueCapcity;
    }

    //带超时的阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            //将timeOunt统一转换为纳秒
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                //nanos返回的是剩余时间
                if (nanos <= 0) {
                    return null;
                }
                try {
                    //返回剩余时间
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    //阻塞获取
    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // fullWaitSet.signal();
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    //阻塞添加
    public void put(T task) {
        lock.lock();
        try {
            while (queue.size() == capcity) {
                try {
                    fullWaitSet.await();
                    //唤醒队列
                    emptyWaitSet.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            //判断队列是否已满
            if (queue.size() == capcity) {
                log.debug("调用者采用哪种模式");
                rejectPolicy.reject(this, task);
            } else {
                //有空闲
                log.debug("加入任务队列{}", task);
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    //带超时时间的阻塞添加
    public Boolean putWithOverTime(T task, long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            long remainTime = timeUnit.toNanos(timeout);
            while (queue.size() == capcity) {
                try {
                    if (remainTime <= 0) {
                        //超时了
                        return false;
                    }
                    remainTime = fullWaitSet.awaitNanos(remainTime);
                    emptyWaitSet.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            return true;
        } finally {
            lock.unlock();
        }

    }

    //获取大小
    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }


}
